package com.example.zcx.base.presenter;


import com.example.zcx.base.view.IView;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 抽象类 统一管理View层绑定和解除绑定
 */
public class BasePresenter <V extends IView> implements IPresenter<V>{

    /**
     * View的弱引用
     */
    private WeakReference<V> reference;
    protected V proxyView;

    public V getView() {
        return proxyView;
    }

    /**
     * 用于检查View是否为空对象
     * @return
     */
    public boolean isAttachView() {
        return this.reference != null && this.reference.get() != null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void attachView(V view) {
        this.reference = new WeakReference<V>(view);
        viewInvocationHandler invocationHandler = new viewInvocationHandler(this.reference.get());
        // 在这里采用动态代理
        proxyView = (V) Proxy.newProxyInstance(
                view.getClass().getClassLoader(), view.getClass()
                        .getInterfaces(), invocationHandler);
        Proxy.getProxyClass(view.getClass().getClassLoader(),view.getClass().getInterfaces());
    }

    @Override
    public void dettachView() {
        if (this.reference != null) {
            this.reference.clear();
            this.reference = null;
        }
    }

    private class viewInvocationHandler implements InvocationHandler {

        private IView view;

        public viewInvocationHandler(IView mView) {
            this.view = mView;
        }

        @Override
        public Object invoke(Object arg0, Method method, Object[] arg2) throws Throwable {
            if (isAttachView()) {
                return method.invoke(view, arg2);
            }
            return null;
        }

    }

}
